<template>
  <div class="app-container">
    <el-steps :active="active" finish-status="success">
      <el-step title="编辑课程信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="最终发布"></el-step>
    </el-steps>
    <el-form :model="chapter" ref="numberValidateForm">
      <el-tag type="danger">注:如果章节中包含小节信息则无法删除,需要完全删除对应的小节信息!</el-tag>
      <br>
      <el-button type="text" @click="openChapterDialog()">添加章节</el-button>
      <!--      添加章节表单组件-->
      <el-dialog title="添加章节" :visible.sync="dialogFormVisible">
        <el-form-item prop="title" label="标题" :label-width="formLabelWidth"
                      :rules="[{ required: true, message: '标题不能为空'},
                        { min: 1, message: '标题最少为一个字符'}]">
          <el-input v-model="chapter.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="sort"
                      :rules="[{ required: true, message: '排序不能为空,且必须为数值类型'},
                        { type: 'number', max:'200000000', message: '排序必须为数字值'}]">
          <el-input v-model.number="chapter.sort" :max="200000000" type="number" auto-complete="off"></el-input>
        </el-form-item>
        <div slot="footer" class="dialog-footer">
          <el-button @click="canel">取 消</el-button>
          <el-button type="primary" @click="onSubmit('numberValidateForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!--      修改章节窗口！！！-->
      <el-dialog title="修改章节" :visible.sync="editdialogVisible">
        <el-form-item prop="title" label="标题" :label-width="formLabelWidth"
                      :rules="[{ required: true, message: '标题不能为空,且必须为数值类型'},
                        { min: 1, message: '标题最少为一个字符'}]">
          <el-input v-model="chapter.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="sort"
                      :rules="[{ required: true, message: '排序不能为空,且必须为数值类型'},
                        { type: 'number', max:'200000000', message: '排序必须为数字值'}]">
          <el-input :max="200000000" :min="0" v-model.number="chapter.sort" type="number"
                    auto-complete="off"></el-input>
        </el-form-item>
        <div slot="footer" class="dialog-footer">
          <el-button @click="canelEdit">取 消</el-button>
          <el-button type="primary" @click="onSubmitEdit('numberValidateForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!--      添加章节表单组件结束-->
      <!-- 添加和修改课时表单 -->
      <el-dialog :close-on-press-escape="false" :show-close="showclose" :visible.sync="dialogVideoFormVisible"
                 :title="eltitle"
                 :close-on-click-modal="false">
        <el-form :model="video" label-width="120px">
          <el-form-item label="课时标题">
            <el-input v-model="video.title"/>
          </el-form-item>
          <el-form-item label="课时排序">
            <el-input-number :min="0" :max="200000000" v-model="video.sort" controls-position="right"/>
          </el-form-item>
          <el-form-item label="是否免费">
            <el-radio-group v-model="video.isFree">
              <el-radio :label="true">免费</el-radio>
              <el-radio :label="false">默认</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 上传视频 TODO -->
          <el-form-item label="上传视频">
            <!--              文件移除-->
            <el-upload
              :on-success="handleVodUploadSuccess"
              :on-remove="handleVodRemove"
              :before-remove="beforeVodRemove"
              :on-exceed="handleUploadExceed"
              :on-error="onError"
              :file-list="fileList"
              :on-progress="progress"
              :action="BASE_API+'eduvod/service/uploadVideo'"
              :limit="1"
              class="upload-demo">
              <el-button size="small" type="primary">上传视频</el-button>
              <el-tooltip placement="right-end">
                <div slot="content">最大支持1G，<br>
                  支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br>
                  GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br>
                  MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br>
                  SWF、TS、VOB、WMV、WEBM 等视频格式上传
                </div>
                <i class="el-icon-question"/>
              </el-tooltip>
            </el-upload>
          </el-form-item>
          <!--          上传视频结束-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-show="show" @click="dialogVideoFormVisible = false">取 消</el-button>
          <el-button v-show="show" type="primary" @click="saveOrUpdateVideo">确 定</el-button>
        </div>
      </el-dialog>
      <!--        添加小节组件结束-->
      <el-form-item>
        <ul class="chanpterList">
          <li
            v-for="chapterVideo in chapterVideoList"
            :key="chapterVideo.id">
            <p>
              {{chapterVideo.title}}

              <span class="acts">
                    <el-button type="text" @click="openVideo(chapterVideo.id)">添加小节</el-button>
                    <el-button type="text" @click="openEditChatper(chapterVideo.id)">编辑章节</el-button>
                    <el-button type="text" @click="removeChapter(chapterVideo.id)">删除章节</el-button>
                </span>
            </p>

            <!-- 视频 -->
            <ul class="chanpterList videoList">
              <li
                v-for="videoVo in chapterVideo.videoVoList"
                :key="videoVo.id">
                <p>
                  {{videoVo.title}}

                  <span class="acts">
                    <el-tag
                      v-if="videoVo.videoOriginalName!=null&&videoVo.videoOriginalName!=undefined&&videoVo.videoOriginalName!=''"
                      style="">
                    视频名称:{{videoVo.videoOriginalName}}
                  </el-tag>
                  <el-tag type="danger" v-else style="">
                    未添加视频
                  </el-tag>
                    <el-button type="text" @click="openEditVideo(videoVo.id)">编辑小节</el-button>
                    <el-button type="text" @click="removeVideo(videoVo.id)">删除小节</el-button>
                </span>
                </p>
              </li>
            </ul>
          </li>
        </ul>

      </el-form-item>
      <el-form-item>
        <el-button style="margin-top: 12px;" @click="prev">上一步</el-button>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import { getchapter, addchapter, editchapter, deletechapter, getchapterByChapterId } from '@/api/edu/chapter'
  import { delchapter } from '../../../api/edu/chapter'
  import { deleteVideo, editVideo, getVideo, saveVideo, deleteAlyVideo } from '@/api/edu/video'

  export default {
    data() {
      return {
        //章节信息
        chapter: {
          id: '',
          title: '',
          sort: 0,
          courseId: this.$route.params.id
        },
        //小节信息
        video: {
          //课程为免费试听状态
          isFree: false,
          courseId: '',
          chapterId: '',
          videoSourceId: ''
        },
        eltitle: '',
        // 嵌套表单长度
        formLabelWidth: '120px',
        // 控制嵌套表单是否显示
        dialogFormVisible: false,
        // 编辑章节组件是否显示
        editdialogVisible: false,
        // 添加章节组件是否显示
        saveBtnDisabled: false,
        // 小节组件是否显示
        dialogVideoFormVisible: false,
        active: 1,
        //课程id
        courseid: '',
        chapterVideoList: [],
        loading: null,
        fileList: [],
        BASE_API: process.env.BASE_API,
        show: true,
        showclose: true
      }
    },
    created() {
      if (this.$route.params && this.$route.params.id) {
        this.courseid = this.$route.params.id
        this.getchapterInfo(this.courseid)
      }
    },
    methods: {
      prev() {
        this.$router.push({ path: '/edu/course/info/' + this.courseid })
      },
      saveOrUpdate() {
        this.$router.push({ path: '/edu/course/publish/' + this.courseid })
      },
      //查课程章节小结
      getchapterInfo(courseid) {
        getchapter(courseid).then(response => {
          this.chapterVideoList = response.data.chapterVideoList
        })
      },
      openChapterDialog() {
        //弹框
        this.fileList = []
        this.dialogFormVisible = true
        //表单数据清空
        this.chapter.title = ''
        this.chapter.sort = 0
      },
      // 取消
      canel() {
        this.dialogFormVisible = false
      },

      //添加课程小结的表单提交方法
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //提交
            this.dialogFormVisible = false
            addchapter(this.chapter).then(response => {
              this.$message.success('添加成功!')
              this.getchapterInfo(this.courseid)
            }).catch(error => {
              this.getchapterInfo(this.courseid)
              this.$message.error('添加失败!')
            })
          } else {
            return false
          }
        })
      },
      //章节删除
      removeChapter(chapterId) {
        this.$confirm('此操作将永久删除该选项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delchapter(chapterId).then(response => {
            this.$message.success('删除成功!')
            this.getchapterInfo(this.courseid)
          }).catch(error => {
            // this.$message.success('删除失败!')
            this.getchapterInfo(this.courseid)
          })
        })
      },
      //打开编辑弹出框
      openEditChatper(chapterId) {
        this.editdialogVisible = true
        getchapterByChapterId(chapterId).then(response => {
          this.chapter = response.data.chapter
        })
      },
      // 取消编辑弹出框
      canelEdit() {
        this.editdialogVisible = false
      },
      onSubmitEdit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //提交
            this.editdialogVisible = false
            editchapter(this.chapter).then(response => {
              this.$message.success('修改成功!')
              this.getchapterInfo(this.$route.params.id)
            }).catch(error => {
              this.$message.error('修改失败!')
              this.getchapterInfo(this.$route.params.id)
            })
          } else {
            return false
          }
        })
      },
      //弹窗
      openVideo(chapterId) {
        this.fileList = []
        this.eltitle = '课时添加'
        this.video = { isFree: true }
        //开启弹窗
        this.video.chapterId = chapterId
        this.video.courseId = this.$route.params.id
        this.dialogVideoFormVisible = true
      },
      //开启弹窗
      closeVideo() {
        this.dialogVideoFormVisible = false
      },
      // 提交小节信息
      saveOrUpdateVideo() {
        // 缺少校验
        //-2147483648 - 2147483647
        //axios提交
        this.closeVideo()
        //添加
        if (this.video.id == null || this.video.id == '' || this.video.id == undefined) {
          saveVideo(this.video).then(response => {
            this.getchapterInfo(this.courseid)
            this.$message.success('添加成功!')
          }).catch(error => {
            this.$message.error('添加失败!')
            this.getchapterInfo(this.courseid)
          })
        } else {
          //修改
          editVideo(this.video).then(response => {
            this.$message.success('修改成功!')
            this.getchapterInfo(this.video.courseId)
          }).catch(error => {
            this.$message.error('修改失败!')
            this.getchapterInfo(this.video.courseId)
          })
        }
        // this.getchapterInfo(this.video.courseId)
      },
      // 编辑小节信息 数据回显
      openEditVideo(videoId) {
        this.fileList = []
        getVideo(videoId).then(response => {
          this.video = response.data.video
          console.log(response.data.video)
        })
        this.eltitle = '课时编辑'
        this.dialogVideoFormVisible = true
      },
      //删除小节
      removeVideo(videoId) {
        deleteVideo(videoId).then(response => {
          this.$message.success('删除成功!')
          this.getchapterInfo(this.video.courseId)
        }).catch(error => {
          this.$message.error('删除失败!')
          this.getchapterInfo(this.video.courseId)
        })
      },
      previous() {
        this.$router.push({ path: '/course/info1/' + this.$route.params.id })
      },
      next() {
        //跳转到第二步
        this.$router.push({ path: '/course/publish3/' + this.$route.params.id })
      },
      //上传成功之后调用
      handleVodUploadSuccess(response, file, fileList) {
        this.video.videoOriginalName = file.name
        this.video.videoSourceId = response.data.videoId
        this.showclose = true
        this.show = true
        this.$message.success('上传成功!')
      },
      //上传中
      progress() {
        this.show = false
        this.showclose = false
      },
      // 文件列表移除文件时的钩子
      handleVodRemove(file, fileList) {
        deleteAlyVideo(this.video.videoSourceId).then(response => {
          this.$notify({
            title: '成功',
            message: '文件已从云端移除!',
            type: 'success'
          })
        })
      },
      //删除之前
      beforeVodRemove(file, fileList) {
        return this.$confirm(`移除后该文件将丢失,确定移除 ${file.name}?`)
      },
      //超出文件总数
      handleUploadExceed(files, fileList) {
        this.$message.warning('想要重新上传视频，请先删除已上传的视频')
      },
      onError() {
        this.$message.error('上传失败!')
        this.showclose = true
        this.show = true
      }
      //
    }
  }
</script>

<style scoped>
  .chanpterList {
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
  }

  .chanpterList li {
    position: relative;
  }

  .chanpterList p {
    float: left;
    font-size: 20px;
    margin: 10px 0;
    padding: 10px;
    height: 70px;
    line-height: 50px;
    width: 100%;
    border: 1px solid #DDD;
    border-radius: 4px;
  }

  .chanpterList .acts {
    float: right;
    font-size: 14px;
  }

  .videoList {
    padding-left: 50px;
  }

  .videoList p {
    float: left;
    font-size: 14px;
    margin: 10px 0;
    padding: 10px;
    height: 60px;
    line-height: 30px;
    width: 100%;
    border: 1px dotted #DDD;
    border-radius: 4px;
  }

</style>
